package com.cr.web.controller.api;

import com.cr.business.domain.dto.SignUpdateDto;
import com.cr.common.config.SystemConfig;
import com.cr.common.core.domain.AjaxResult;
import com.cr.common.utils.file.Base64DecodedMultipartFile;
import com.cr.common.utils.file.FileUploadUtils;
import com.cr.common.utils.file.MimeTypeUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * 文件上传控制类
 */
@RestController
@RequestMapping("api/file")
@Validated
public class FileController {

    /**
     * 签名上传
     */
    @PostMapping("/updateSign")
    public AjaxResult sign(@Valid @RequestBody SignUpdateDto dto) throws Exception
    {
        MultipartFile file = Base64DecodedMultipartFile.base64Convert(dto.getBase64(), "sign.png");
        if (!file.isEmpty()) {
            String avatar = FileUploadUtils.upload(SystemConfig.getUserSignPath(), file, MimeTypeUtils.IMAGE_EXTENSION, true);
            return AjaxResult.successOneData("img", avatar);
        }
        return AjaxResult.error("上传签名异常！");
    }

    /**
     * 证照上传
     */
    @PostMapping("/updateCert")
    public AjaxResult updateCert(@NotNull(message = "文件不能为空！") @RequestParam(value = "file") MultipartFile file) throws Exception
    {
        if (file != null && !file.isEmpty()) {
            String avatar = FileUploadUtils.upload(SystemConfig.getCertPath(), file, MimeTypeUtils.IMAGE_EXTENSION, true);
            return AjaxResult.successOneData("img", avatar);
        }
        return AjaxResult.error("上传图片异常！");
    }

}
